// pages/searchMemo/index.js
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
const app = getApp();
const db = wx.cloud.database();
const _ = db.command
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //是否开启搜索框浮动
    hideTop: false,
    //搜索值
    searchKey: '',
    actions: [
      {
        name: '删除',
        color: '#fff',
        fontsize: '20',
        width: 100,
        icon: 'delete_fill',
        background: '#ed3f14'
      },
      {
        name: '返回',
        width: 100,
        color: '#80848f',
        fontsize: '20',
        icon: 'undo'
      }
    ],
    //备忘录列表
    memoList: [],
    // 加载数据相关
    page: 0,
    pageSize: 10,
    count: 0,
    //加载显示
    loadStatis: false,
    isLoad: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    var searchKey = that.data.searchKey;
    //搜索备忘录
    var page = 0;
    var pageSize = that.data.pageSize;
    var memoList = [];
    if (searchKey) {
      searchMemo(that, page, pageSize, memoList, searchKey);
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;
    var page = that.data.page;
    var pageSize = that.data.pageSize;
    var memoList = that.data.memoList;
    var searchKey = that.data.searchKey;
    that.setData({
      loadStatis: true,
      page: page + 1,
      isLoad: true
    })
    //获取备忘列表
    searchMemo(that, page + 1, pageSize, memoList, searchKey);
  },

  //页面滚动监听
  onPageScroll: function ({ scrollTop }) {
    let that = this;
    if (scrollTop >= 54) {
      that.setData({
        hideTop: true
      })
    } else {
      that.setData({
        hideTop: false
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    // 设置分享标题
    return {
      title: app.globalData.shareTitle,
      path: '/pages/index/index'
    }
  },

  /**
   * 取消搜索事件
   */
  onClear: function () {
    var that = this;
    that.setData({
      memoList: []
    })
  },

  /**
   * 搜索事件
   */
  onSearch: function ({ detail }) {
    var that = this;
    //搜索备忘录
    if (detail) {
      var page = 0;
      var pageSize = that.data.pageSize;
      var memoList = [];
      searchMemo(that, page, pageSize, memoList, detail);
    } else {
      that.setData({
        searchKey: '',
        memoList: []
      })
    }
  },
  /**
   * 进入修改/查看备忘页面
   */
  onUpdateMemo: function ({ currentTarget }) {
    const { memoid } = currentTarget.dataset;
    if (memoid) {
      wx.navigateTo({
        url: '/pages/editMemo/index?memoId=' + memoid,
      })
    } else {
      Toast('获取该备忘录信息为空')
    }
  },

  /**
   * 点击右侧按钮监听事件
   */
  onCloseButton: function ({ currentTarget, detail }) {
    var that = this;
    const { memoid } = currentTarget.dataset;
    const { title } = currentTarget.dataset;
    const index = detail.index;
    if (0 === index) {
      //等于0时为删除
      Dialog.confirm({
        title: '提醒',
        message: '您确定要删除【' + title + '】这条备注吗？'
      })
        .then(() => {
          //删除备忘信息
          deleteMemo(that, memoid);
        })
    }
  }
})

/**
 * 搜索备忘录
 * @param {*} that 
 * @param {*} searchKey 
 */
function searchMemo(that, page, pageSize, memoList, searchKey) {
  // 搜索中状态
  Toast.loading({
    message: '搜索中...',
    forbidClick: true,
  });

  db.collection(app.globalData.memoCollection)
    .where(
      _.or([
        {
          title: db.RegExp({
            regexp: searchKey,
            //从搜索栏中获取的searchKey作为规则进行匹配。
            options: 'i',
            //大小写不区分
          })
        },
        {
          content: db.RegExp({
            regexp: searchKey,
            //从搜索栏中获取的searchKey作为规则进行匹配。
            options: 'i',
            //大小写不区分
          })
        }
      ])
    )
    .orderBy('status', 'ase') //先按照状态排序
    .orderBy('level', 'desc')//再按照等级排序
    .skip(page * pageSize)
    .limit(pageSize)
    .get().then(res => {
      // 清除搜索中状态
      Toast.clear();
      // res.data 是一个包含集合中有权限访问的所有记录的数据，不超过 20 条
      if (res.data.length != 0) {
        that.setData({
          memoList: memoList.concat(res.data),
          page: page,
          searchKey: searchKey
        })
      } else {
        if (memoList.length >= 10) {
          that.setData({
            memoList: memoList.concat(res.data),
            loadStatis: true,
            isLoad: false,
            searchKey: searchKey
          })
        } else {
          // 不够10个不出现已加载全部
          that.setData({
            memoList: memoList.concat(res.data),
            loadStatis: false,
            isLoad: true,
            searchKey: searchKey
          })
        }
      }
    })
    .catch(error => {
      // 清除搜索中状态
      Toast.clear();
      Toast.loading({
        type: 'text',
        duration: 1500,
        message: error.errMsg
      });
    });
}


/**
 * 刪除备忘信息
 */
function deleteMemo(that, memoid) {
  db.collection(app.globalData.memoCollection).doc(memoid)
    .remove()
    .then(res => {
      var stats = res.stats;
      if (stats && stats.removed > 0) {
        that.onShow();
        Toast.loading({
          type: 'text',
          duration: 1500,
          message: "刪除成功"
        });
      }
    })
    .catch(error => {
      Toast.loading({
        type: 'text',
        duration: 1500,
        message: error.errMsg
      });
    })
}